package com.zj.java21demo.config;

import com.zj.java21demo.exception.CustomAuthenticationEntryPoint;
import com.zj.java21demo.exception.CustomLogoutSuccessHandler;
import com.zj.java21demo.filter.CustomUserDetailsService;
import com.zj.java21demo.filter.JwtAuthenticationTokenFilter;
import com.zj.java21demo.utils.JwtTokenByJdk21Util;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import static org.springframework.http.HttpMethod.*;
import static org.springframework.http.HttpMethod.DELETE;

/**
 * @Version 1.0.0
 * @Date 2024/2/28 16:35
 * @Created by zhangjun
 */
@EnableWebSecurity
@Configuration
@EnableMethodSecurity(securedEnabled = true, jsr250Enabled = true)
@AllArgsConstructor
public class SecurityConfig {
    private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

    private JwtTokenByJdk21Util jwtTokenByJdk21Util;

    private CustomUserDetailsService customUserDetailsService;

//    private static final String[] WHITE_LIST_URL = {
//            "/auth/**",
//            "/ws/**",
//            "/tUser/addUser"
//            };


    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                // cors启用
                .cors(httpSecurityCorsConfigurer -> {})
                // CSRF(跨站请求伪造)禁用，因为不使用session
                .csrf(AbstractHttpConfigurer::disable)
                .csrf().disable()

                // 基于token，所以不需要session，无状态
                .sessionManagement(configurer -> configurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 过滤请求
                .authorizeHttpRequests(
                        registry -> registry
                                .requestMatchers("/ws/**").anonymous()
                                .requestMatchers("/auth/**").anonymous()
                                .requestMatchers("/tUser/addUser").anonymous()
                                // 除上面外的所有请求全部需要鉴权认证
                                .anyRequest().authenticated()
                )

//                .authorizeHttpRequests(req ->
//                        req.requestMatchers(WHITE_LIST_URL)
//                                .permitAll()
////                                .requestMatchers("/api/v1/management/**").hasAnyRole(ADMIN.name(), MANAGER.name())
////                                .requestMatchers(GET, "/api/v1/management/**").hasAnyAuthority(ADMIN_READ.name(), MANAGER_READ.name())
////                                .requestMatchers(POST, "/api/v1/management/**").hasAnyAuthority(ADMIN_CREATE.name(), MANAGER_CREATE.name())
////                                .requestMatchers(PUT, "/api/v1/management/**").hasAnyAuthority(ADMIN_UPDATE.name(), MANAGER_UPDATE.name())
////                                .requestMatchers(DELETE, "/api/v1/management/**").hasAnyAuthority(ADMIN_DELETE.name(), MANAGER_DELETE.name())
//                                .anyRequest()
//                                .authenticated()
//                )
                .logout(configurer -> configurer
                        .logoutUrl("/logout")
//                        .logoutSuccessHandler(customLogoutSuccessHandler)
                        .logoutSuccessHandler((request, response, authentication) -> SecurityContextHolder.clearContext())
                )
                .headers(configurer -> configurer.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))
//                .authenticationProvider(authenticationProvider)
//                .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(new JwtAuthenticationTokenFilter(jwtTokenByJdk21Util, customUserDetailsService), UsernamePasswordAuthenticationFilter.class)

                // 认证失败处理类
                .exceptionHandling(configure -> {
                    configure.authenticationEntryPoint(customAuthenticationEntryPoint);
                })
        ;
        return httpSecurity.build();
    }

    @Bean
    public WebSecurityCustomizer ignoringCustomizer() {
        return (web) -> web.ignoring().requestMatchers("/tUser/addUser");
    }


    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


}
